package me.sdevil507.supports.shiro.matcher;

import me.sdevil507.biz.common.sms.captcha.enums.CaptchaType;
import me.sdevil507.biz.common.sms.captcha.exceptions.CaptchaInvalidException;
import me.sdevil507.biz.common.sms.captcha.service.CaptchaService;
import me.sdevil507.supports.shiro.token.SmsToken;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 短信登录验证匹配Matcher
 *
 * @author sdevil507
 */
public class SmsMatcher extends SimpleCredentialsMatcher {

    @Autowired
    private CaptchaService captchaService;

    /**
     * 重写凭证验证方法
     *
     * @param token 令牌
     * @param info  信息
     * @return boolean
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        // 获取手机登录名
        String phoneNumber = (String) token.getPrincipal();
        // 获取验证码
        String captcha = ((SmsToken) token).getCaptcha();
        boolean checkCaptchaState = captchaService.check(CaptchaType.LOGIN, phoneNumber, captcha);
        if (checkCaptchaState) {
            // 如果验证成功
            return true;
        } else {
            // 如果验证失败
            throw new CaptchaInvalidException("登录验证码无效!");
        }
    }
}
